library(ggplot2)
library(lme4) # lmer()
library(lmerTest) # p-values for lmer() (load after lme4)
library(glmnet) # ridge, lasso, cv.glmnet()
orch <- read.csv("https://greymonroe.github.io/PLS_206/data/almond_orchards.csv")
wheat <- read.csv("https://greymonroe.github.io/PLS_206/data/wild_wheat.csv")Problem Set 6: Shrinkage and Cross-Validation
PLS 206 — Applied Multivariate Modeling
Due: Monday, November 9, 1:10 PM (start of class) — submitted through Canvas.
Questions 1–6 use Monday’s lecture (mixed models, shrinkage, ridge and lasso). Questions 7–10 use Wednesday’s (cross-validation, choosing λ, the traps). The week’s code page has working code for every step; the hints point to its parts and sections.
Submission Instructions
Upload two files to Canvas:
- Written answers — a
.pdfdocument with your written responses, interpretations, and figures. - R script — a
.Rfile with all the code you used to produce your answers.
List the first and last names of any collaborators in both files.
Naming convention: HW6emailID.R (code) and HW6emailID.pdf (written answers), where emailID is the part of your UC Davis email before the @.
Example: Grey Monroe would submit
HW6gmonroe.RandHW6gmonroe.pdf.
Feel free to use Google, StackOverflow, and other resources if you are stuck with code, and post questions on Slack if anything is unclear.
Every model you plot: show the raw data, the fitted curve, and its 95% confidence band, with the response on the y-axis.
The data
Almond orchards (Part 1 and Q10). Kernel yield (yield, kg per tree) of 174 trees in 14 almond orchards, with 3 to 30 trees measured per orchard. canopy is the percentage of midday light the tree’s canopy intercepts, measured tree by tree. Seven of the 14 growers apply a mycorrhizal inoculant to the whole orchard; the other seven do not. These data are simulated, so we know the truth and can check what each method finds.
Wild wheat (Parts 2 and 3). Flowering time of 54 wild einkorn genotypes grown in a common garden, with the 19 bioclimatic variables of each genotype’s home site. You used these data in Problem Sets 2 and 5. In Problem Set 5 you chose predictors one model at a time; this week you shrink instead.
Part 1: Trees Within Orchards
Q1. Fit yield ~ canopy three ways: ignoring orchard (lm), with orchard as a fixed factor (lm(yield ~ canopy + orchard)), and with orchard as a random intercept (lmer(yield ~ canopy + (1 | orchard))). Report the canopy slope and its standard error from each. From the mixed model, report the orchard-to-orchard SD and the residual SD. Plot yield against canopy, coloured by orchard, with the line and 95% band from the model that ignores orchard. In one or two sentences, explain why that model’s residual SD is larger than the mixed model’s.
coef(summary(m))["canopy", ] for each model; VarCorr(m_mix) for the two SDs; sigma(m_pool) for the residual SD of the plain lm(). For the band, predict(m_pool, newdata, interval = "confidence") on a grid of canopy values. Code page Part B, sections 5, 6 and 8; slides Three ways to treat farm and In R: lmer().
Q2. Shrinkage. For each orchard, compare its effect estimated on its own (from the fixed-factor model) with its random effect (ranef()). Use the code below to line them up, then plot random against fixed with a 1:1 line, labelling each point with its number of trees. Which orchards move most toward zero, and why? For orchard02 (3 trees) and orchard11 (18 trees), compare random / fixed with the shrinkage weight σ²_orchard / (σ²_orchard + σ² / n).
ids <- sort(unique(orch$orchard))
fe <- coef(m_fix)
fixed <- c(0, fe[paste0("orchard", ids[-1])]) + fe[1] - fixef(m_mix)[1]
random <- ranef(m_mix)$orchard[ids, 1]
n <- as.numeric(table(orch$orchard)[ids])The two SDs are in VarCorr(m_mix): sd_o <- attr(VarCorr(m_mix)$orchard, "stddev") and s <- sigma(m_mix). Then w <- sd_o^2 / (sd_o^2 + s^2 / n). Code page Part B, section 7; slide Shrinkage: small farms borrow strength.
Q3. Does the inoculant raise yield? Test it two ways: lm(yield ~ canopy + inoculant) and lmer(yield ~ canopy + inoculant + (1 | orchard)) (with lmerTest loaded). Report the estimate, SE and p-value from each, and the denominator degrees of freedom from the mixed model. Which result would you report, and what is the real sample size for testing the inoculant?
coef(summary(m))["inoculantyes", ]. Ask yourself what the growers decided: the inoculant was applied to whole orchards, not to trees. Code page Part B, sections 9 and 10; slides p-values: load lmerTest instead and Why it matters: a treatment chosen per farm.
Q4. Do orchards differ in how yield responds to canopy? Centre and rescale canopy first (orch$canopy10 <- (orch$canopy - 65) / 10, the change per 10 percentage points), then compare a random-intercept model with a random-slope model, (canopy10 | orchard), using anova(m1, m2, refit = FALSE). What does the test say, and which model would you keep?
Fit both with lmer(). refit = FALSE compares the REML fits, which is right when the two models have the same fixed effects. Look at the SD of canopy10 in VarCorr(m2) as well as the p-value. Code page Part B, section 11; slide Do farms respond differently? Random slopes.
Part 2: Ridge and Lasso
Use the 18 bioclimatic variables (all except bio7, which is bio5 − bio6), scaled:
vars <- setdiff(paste0("bio", 1:19), "bio7")
X <- scale(as.matrix(wheat[, vars]))
y <- wheat$FloweringQ5. Fit lm(y ~ X) and look at the coefficients: one standard deviation of a climate variable, in days of flowering time. Which is the largest, and is it believable given that flowering time has an SD of about 10 days? Now fit ridge regression (glmnet(X, y, alpha = 0)) and plot the coefficient paths. Report the coefficients at λ = 1 and at the largest λ in the path. What does the ridge model predict for every genotype at the largest λ? Why did we scale the predictors first?
plot(ridge, xvar = "lambda"); coef(ridge, s = 1); coef(ridge, s = max(ridge$lambda)). Compare sapply(wheat[, vars], sd): the penalty adds up the squared slopes, so it must treat every variable on the same scale. Code page Part C, sections 16 and 17; slides Scale the predictors first, Turn the dial: λ and Ridge paths: every slope shrinks, none hits zero.
Q6. Fit the lasso (alpha = 1) and plot its paths. Which variable enters first as λ decreases, and over what range of λ is it the only one in the model? How does that compare with what forward stepAIC() chose in Problem Set 5 Q9? What does the lasso do that ridge cannot?
lasso <- glmnet(X, y, alpha = 1); lasso$df is the number of nonzero coefficients at each lasso$lambda. To find the order of entry: apply(as.matrix(lasso$beta) != 0, 1, function(z) which(z)[1]). Code page Part C, section 18; slides Lasso paths: slopes hit exactly zero and In R: glmnet().
Part 3: Cross-Validation
Q7. Choose λ by 10-fold cross-validation: set.seed(206); cv <- cv.glmnet(X, y, alpha = 1). Plot cv. Report lambda.min and lambda.1se, the variables each keeps, and the cross-validated RMSE at each (the square root of cv$cvm). Rerun with set.seed(1) through set.seed(5): which of the two choices gives the same variables every time?
coef(cv, s = "lambda.min") and coef(cv, s = "lambda.1se"); sqrt(cv$cvm[cv$lambda == cv$lambda.min]). The 1-SE rule takes the largest λ whose CV error is within one standard error of the minimum. Code page Part D, sections 27 and 28; slides cv.glmnet(): the CV error along λ, lambda.min or lambda.1se? and Folds are random: so is λ.
Q8. Compare four models by 10-fold CV, with the same folds for all four: the null model (predict the mean), Flowering ~ bio1, lm() with all 18 variables, and the lasso. Start with set.seed(206); fold <- sample(rep(1:10, length.out = nrow(wheat))). For the lasso, run cv.glmnet() on the training folds only, inside the loop, and predict with lambda.1se. Report the four RMSEs. Rank them, and explain why the 18-variable model does so badly on held-out genotypes.
In the loop: tr <- fold != k; fit on wheat[tr, ], predict wheat[!tr, ], store the predictions; RMSE = sqrt(mean((observed - predicted)^2)) over all 54 at the end. For the lasso use as.matrix(wheat[tr, vars]) (glmnet scales internally) and predict(cvk, newx, s = "lambda.1se"). Choosing λ inside the loop keeps the held-out fold out of every decision. Code page Part D, sections 25 and 29; slides k-fold: every farm gets a turn and Compare whole recipes on unseen farms.
Q9. Select inside the folds. Run this block exactly as written. It makes 200 columns of pure noise and picks the five most correlated with flowering time.
set.seed(206)
noise <- matrix(rnorm(54 * 200), 54, 200, dimnames = list(NULL, paste0("n", 1:200)))
yy <- wheat$Flowering
top5 <- order(-abs(cor(noise, yy)))[1:5]
fold <- sample(rep(1:10, length.out = 54))- Cross-validate
lm(y ~ .)on those five columns, chosen once on all 54 rows. (b) Now redo the choice inside the loop: in each fold, pick the five columns most correlated withyyin the training rows only, then fit and predict. Report both RMSEs and the null model’s RMSE. Which is honest, and what went wrong in (a)?
For (b), inside the loop: tk <- order(-abs(cor(noise[tr, ], yy[tr])))[1:5]. The noise columns are unrelated to flowering time by construction, so an honest CV error cannot beat the null model. Code page Part E, section 30; slides Trap: choose predictors first, then cross-validate and Screened outside the folds: fooled every time.
Q10. Back to the orchards. Use the random-intercept model yield ~ canopy + (1 | orchard) to predict yield two ways: (a) 10-fold CV with trees assigned to folds at random (set.seed(206)), and (b) leave one orchard out: hold out all the trees of one orchard, fit on the other 13, predict the held-out trees, and repeat for all 14. Report both RMSEs. Which number would you give a grower who is not in the data set, and why is it larger?
predict(m, newdata, allow.new.levels = TRUE): for an orchard the model has seen, the prediction includes that orchard’s random effect; for a new orchard, it is the average orchard. Compare both RMSEs with the two SDs from Q1. Code page Part E, section 31; slide Trap: rows that come in groups.